package com.smartrobot.smartrobot.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Contacts;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.adapter.DetailListViewAdapter;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.util.FileUtil;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.NetWorkUtil;
import com.smartrobot.smartrobot.util.Schedule;
import com.smartrobot.smartrobot.util.TimeUtil;
import com.smartrobot.smartrobot.util.User;
import com.smartrobot.smartrobot.view.ExTopListView;
import com.smartrobot.smartrobot.view.ToastCustom;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/1/7.
 */
public class ScheduleActivity extends Activity implements View.OnClickListener,ExTopListView.UdateNewListener {

    private RelativeLayout detailLayout;
    private ExTopListView todayListView,tomorrowListView,nextTomorrowListView;
    private ImageView back;
    private ViewPager viewPager;
    private List<View> views;
    private List<Schedule> todayList,tomorrowList,nextTomorrowList;
     ImageView add;
    private DetailListViewAdapter todayAdapter,tomorrowAdapter,nextTomorrowAdapter;
    private TextView call,detailDay,progressTxt,titleTxt;
    private int currentPos;
    private boolean isGetSchedule;
    private int role;
    private long time = 0;
    private Map<String,String> map;

    public  static ScheduleActivity scheduleInstance;

    //弹出栏控件
    AlertDialog dialog = null;
     LinearLayout progressLayout;
    ProgressBar progressBar;
    TextView txt ;


    private String todayFileName = FileUtil.detailCachePath
            +User.getInstance().getId()+ User.getInstance().getPhone()+TimeUtil.getTodayData()
            + FileUtil.detailEndName;

    private String tomorrowFileName = FileUtil.detailCachePath
            +User.getInstance().getId()+ User.getInstance().getPhone()+TimeUtil.getTomoData()
            + FileUtil.detailEndName;

    private String nextTomorrowFileName = FileUtil.detailCachePath
            +User.getInstance().getId()+ User.getInstance().getPhone()+TimeUtil.getTheDayData()
            + FileUtil.detailEndName;



    private ScheduleHandler handler;
    private final int HANDLER_READ_FILE = 1011;
    private final int HANDLER_READ_SERVER = 1012;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null){
            throw new NullPointerException();
        }
        this.setContentView(R.layout.page_schedule);

        scheduleInstance = this;

        if(getIntent().getStringExtra("notiId") != null)
        {
            //隐藏nitification
            NotificationManager notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.cancel(HttpUtil.GET_DETAIL_ONEDAY_SCHEDULE_SUCCESS);
        }
        init();

    }


    void init(){
        LogToSd.log_init();
        HttpUtil.init(getApplicationContext());
        handler = new ScheduleHandler();
        isGetSchedule = false;
        initView();


    }

    void initView(){

        viewPager = (ViewPager)findViewById(R.id.detail_viewpager);
        add = (ImageView)findViewById(R.id.detail_add);
        call = (TextView)findViewById(R.id.detail_call_him);
        detailDay = (TextView)findViewById(R.id.detail_day);
        progressTxt = (TextView)findViewById(R.id.detail_progressTxt);
        titleTxt = (TextView)findViewById(R.id.detail_titleName);
        back = (ImageView)findViewById(R.id.detail_back);
        detailLayout = (RelativeLayout)findViewById(R.id.detail_detail_layout);

        todayList = new ArrayList<Schedule>();
        tomorrowList = new ArrayList<Schedule>();
        nextTomorrowList = new ArrayList<Schedule>();


        views = new ArrayList<View>();
        View todayView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_schedule_listview, null);
        View tomorrowView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_schedule_listview, null);
        View nextTomorrowView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_schedule_listview,null);

        todayListView = (ExTopListView)todayView.findViewById(R.id.detail_listView);
        tomorrowListView = (ExTopListView)tomorrowView.findViewById(R.id.detail_listView);
        nextTomorrowListView = (ExTopListView)nextTomorrowView.findViewById(R.id.detail_listView);


        views.add(todayView);
        views.add(tomorrowView);
        views.add(nextTomorrowView);



        // 重写ViewPager适配器
        PagerAdapter pagerAdapter = new PagerAdapter() {

            @Override
            public boolean isViewFromObject(View view, Object object) {
                // TODO Auto-generated method stub
                return view == object;
            }

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return views.size();
            }

            @Override
            public Object instantiateItem(View container, int position) {
                ((ViewPager) container).addView(views.get(position), 0);
                return views.get(position);
            }

            @Override
            public void destroyItem(View container, int position, Object object) {
                // 删除某个view
                ((ViewPager) container).removeView(views.get(position));

            }

            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {

                //可以在这个界面初始化

                super.setPrimaryItem(container, position, object);
            }

        };

        todayAdapter = new DetailListViewAdapter(getApplicationContext());
        tomorrowAdapter = new DetailListViewAdapter(getApplicationContext());
        nextTomorrowAdapter = new DetailListViewAdapter(getApplicationContext());

        todayListView.setAdapter(todayAdapter);
        tomorrowListView.setAdapter(tomorrowAdapter);
        nextTomorrowListView.setAdapter(nextTomorrowAdapter);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(0);
        currentPos = 0;
//

        todayListView.setOnUdateNewListender(this);
        tomorrowListView.setOnUdateNewListender(this);
        nextTomorrowListView.setOnUdateNewListender(this);
        add.setOnClickListener(this);
        call.setOnClickListener(this);
        back.setOnClickListener(this);


        //使用线程
        Thread thread = new Thread(new InitThread());
        thread.start();

        if(User.getInstance().getRole().equals("客户")){

            role = 0;
            titleTxt.setText("我的理发师日程");
            add.setVisibility(View.GONE);//不可以添加修改日程
        }else{

            role = 1;
            titleTxt.setText("我的日程");
        }


        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {

            }

            @Override
            public void onPageSelected(int i) {

                if(i == 0)
                {
                    if(time != 0)
                        detailDay.setText("今天 "+TimeUtil.getTodayData(time));
                    else
                        detailDay.setText("今天 ");
                    currentPos = 0;
                }
                if(i == 1)
                {
                    if(time != 0)
                        detailDay.setText("明天 "+TimeUtil.getTomoData(time));
                    else
                        detailDay.setText("明天 ");
                    currentPos = 1;
                }
                if(i == 2)
                {
                    if(time != 0)
                        detailDay.setText("后天 "+TimeUtil.getTheDayData(time));
                    else
                        detailDay.setText("后天 ");
                    currentPos = 2;
                }


            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });


    }

    @Override
    public void updateNew() {//监听listview向下拉动

        switch(currentPos){

            case 0://刷新今天的日程

                Log.d(" ----刷新今天的日程---- ","今天");
                if(!isGetSchedule){
                    isGetSchedule = true;
                    todayList.clear();
                    map = new HashMap<String, String>();
                    map.put("type","0");
                    HttpUtil.apiGetOneDaySchedule(map,todayList,handler);

                }

                break;
            case 1://刷新明天的日程

                Log.d(" ----刷新明天的日程---- ","明天");
                if(!isGetSchedule){
                    isGetSchedule = true;
                    tomorrowList.clear();
                    map = new HashMap<String, String>();
                    map.put("type","1");
                    HttpUtil.apiGetOneDaySchedule(map,tomorrowList,handler);

                }

                break;
            case 2://刷新后天的日程

                Log.d(" ----刷新后天的日程---- ","后天");
                if(!isGetSchedule){
                    isGetSchedule = true;
                    nextTomorrowList.clear();
                    map = new HashMap<String, String>();
                    map.put("type","2");
                    HttpUtil.apiGetOneDaySchedule(map,nextTomorrowList,handler);

                }

                break;

        }

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){

            case R.id.detail_back:
                ScheduleActivity.this.finish();
                break;

            case R.id.detail_add://添加日程

                LayoutInflater inflater = getLayoutInflater();
                final View layout = inflater.inflate(R.layout.page_schedule_add,null);

                progressLayout = (LinearLayout)layout.findViewById(R.id.schedule_add_layout);
                progressBar = (ProgressBar)layout.findViewById(R.id.schedule_add_progress);
                txt = (TextView)layout.findViewById(R.id.schedule_add_progressTxt);

                final TimePicker timePicker = (TimePicker)layout.findViewById(R.id.schedule_add_time);
                timePicker.setIs24HourView(true);
                dialog = new AlertDialog.Builder(this).setView(layout)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {

                                String event = ((TextView)layout.findViewById(R.id.schedule_add_event)).getEditableText().toString();

                                if(event.length() != 0){

                                    txt.setText("正在加载...");
                                    progressBar.setVisibility(View.VISIBLE);

                                    String time = "";
                                    if(timePicker.getCurrentHour()<10)
                                        time = "0"+timePicker.getCurrentHour();
                                    else
                                        time = ""+timePicker.getCurrentHour();

                                    if(timePicker.getCurrentMinute()<10)
                                        time = time + "0"+timePicker.getCurrentMinute();
                                    else
                                        time = time + timePicker.getCurrentMinute();


                                   //发送日程到服务器再更新
                                   switch(currentPos)
                                   {
                                       case 0:
                                           if(!isGetSchedule){
                                           isGetSchedule = true;
                                           map = new HashMap<String, String>();
                                           map.put("type","0");
                                           map.put("matter",event);
                                           map.put("time",time);
                                           todayList.clear();
                                           HttpUtil.apiSendSchedule(map,todayList,handler);
                                           }
                                           break;
                                       case 1:
                                           if(!isGetSchedule) {
                                               isGetSchedule = true;
                                               map = new HashMap<String, String>();
                                               map.put("type", "1");
                                               map.put("matter", event);
                                               map.put("time", time);
                                               tomorrowList.clear();
                                               HttpUtil.apiSendSchedule(map, tomorrowList, handler);
                                           }
                                           break;
                                       case 2:
                                           if(!isGetSchedule) {
                                               isGetSchedule = true;
                                               map = new HashMap<String, String>();
                                               map.put("type", "2");
                                               map.put("matter", event);
                                               map.put("time", time);
                                               nextTomorrowList.clear();
                                               HttpUtil.apiSendSchedule(map, nextTomorrowList, handler);
                                           }
                                           break;

                                   }

                                       progressLayout.setVisibility(View.VISIBLE);
                                      canCloseDialog(dialog, false);//不关闭对话框
                                }else{
                                    ToastCustom.showToast(getApplicationContext(),"日程不能为空");
                                    canCloseDialog(dialog, false);//不关闭对话框
                                }


                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                canCloseDialog(dialog, true);//不关闭对话框
                            }
                        }).show();
                dialog.setCanceledOnTouchOutside(true);



                break;

            case R.id.detail_call_him://拨打电话

//                if(role == 0) {//顾客可以拨打理发师电话
                    //拨打电话
                Intent DialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+""));
                startActivity(DialIntent);
//                }else{//若是理发师就打开通讯录让他打电话
//                    //调用联系人界面
////                    Intent intent= new Intent("com.android.contacts.action.LIST_STREQUENT");
////                    intent.setClassName("com.android.contacts","com.android.contacts.DialtactsActivity");
////                    startActivity(intent);
//
//                    Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_PICK);
//                    intent.setData(ContactsContract.Contacts.CONTENT_URI);
//                    startActivity(intent);
//                }







                break;

        }

    }

    //  控制dialog点击某部分后不消失
    private void canCloseDialog(DialogInterface dialogInterface, boolean close) {
        try {
            Field field = dialogInterface.getClass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialogInterface, close);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void NotiServerDataChange(){

        //使用线程 更新服务器信息
        Thread thread = new Thread(new InitThread());
        thread.start();


    }



    class InitThread implements Runnable{

        @Override
        public void run() {

            try {

                Looper.prepare();
                //获取网络时间
                Log.d("===============================>","开启线程正在获取网络时间");
                if(NetWorkUtil.isHasNetWork(getApplicationContext()))
                              time =  TimeUtil.getNetTime();
                else
                              time = 0;
                Log.d("===============================>","开启线程正在获取缓存文件");

                if(!(new File(todayFileName).exists()) && !(new File(tomorrowFileName).exists()) && !(new File(nextTomorrowFileName).exists()) )
                {
                    //第一次获取日程
                    Message msg = new Message();
                    msg.what = HANDLER_READ_SERVER ;
                    handler.sendMessage(msg);

                }else
                {
                    todayList  = FileUtil.readScheduleToFile(todayFileName);
                    tomorrowList  = FileUtil.readScheduleToFile(tomorrowFileName);
                    nextTomorrowList  = FileUtil.readScheduleToFile(nextTomorrowFileName);

                    if(todayList.size() == 0 && tomorrowList.size() == 0 && nextTomorrowList.size() == 0){
                        Message msg = new Message();
                        msg.what = HANDLER_READ_SERVER ;
                        handler.sendMessage(msg);
                    }else{
                        Message msg = new Message();
                        msg.what = HANDLER_READ_FILE ;
                        handler.sendMessage(msg);
                }


                }

            } catch (Exception e) {

                //上面个已经发送了请求了

//                e.printStackTrace();
                Message msg = new Message();
                msg.what = HANDLER_READ_SERVER ;
                handler.sendMessage(msg);

                Log.e("=============>","日程读取错误");
                LogToSd.debug("日程读取错误，不用处理,因为没有文件就夹,向服务器请求数据");

            }


        }
    }


    class ScheduleHandler extends Handler {

        @Override
        public void dispatchMessage(Message msg) {


            switch (msg.what){

                case HANDLER_READ_FILE://读取文件成功

                    if( currentPos == 0 && time != 0)
                        detailDay.setText("今天 "+TimeUtil.getTodayData(time));
                    else
                        detailDay.setText("今天 ");

                    //通知更新
                    todayAdapter.notiDataChangeList(todayList);
                    tomorrowAdapter.notiDataChangeList(tomorrowList);
                    nextTomorrowAdapter.notiDataChangeList(nextTomorrowList);

                    progressTxt.setVisibility(View.GONE);
                    detailLayout.setVisibility(View.VISIBLE);

                    isGetSchedule = false;

                    break;

                case HANDLER_READ_SERVER://读取文件成功

                    if( currentPos == 0 && time != 0)
                        detailDay.setText("今天 "+TimeUtil.getTodayData(time));
                    else
                        detailDay.setText("今天 ");

                    //到服务器里面获得数据
                    if(!isGetSchedule){
                        if(role != 0){
                            isGetSchedule = true;
                            Log.d("-------------->","没有数据--到服务器里获取");
                            todayList.clear();
                            tomorrowList.clear();
                            nextTomorrowList.clear();
                            HttpUtil.apiGetSchedule(new HashMap<String, String>(), todayList, tomorrowList, nextTomorrowList, handler);
                        }else{
                            progressTxt.setVisibility(View.GONE);
                            detailLayout.setVisibility(View.VISIBLE);
                            isGetSchedule = false;
                        }

                    }

                    break;

                case HttpUtil.GET_DETAIL_SCHEDULE_SUCCESS:

                    //通知更新
                    todayAdapter.notiDataChangeList(todayList);
                    tomorrowAdapter.notiDataChangeList(tomorrowList);
                    nextTomorrowAdapter.notiDataChangeList(nextTomorrowList);

                    //隐藏加载组件
                    progressTxt.setVisibility(View.GONE);
                    detailLayout.setVisibility(View.VISIBLE);
                    isGetSchedule = false;

                    Log.d("-------------->","更新数据成功");

                    break;

                case HttpUtil.GET_DETAIL_SCHEDULE_FAILD:
                case HttpUtil.GET_DETAIL_ONEDAY_SCHEDULE_FAILD:
                    isGetSchedule = false;

                    if(msg.obj != null){

                        if(msg.obj.toString().equals("100")){//未登录，帮助用户重新登录,然后再获取一次
                            isGetSchedule = true;
                            todayList.clear();
                            tomorrowList.clear();
                            nextTomorrowList.clear();
                            HttpUtil.reLogin(getApplication(),handler);

                        }

                        if(msg.obj.toString().equals("101")){
                            progressTxt.setText("您没有加入理发师，无法查看");
                            progressTxt.setVisibility(View.VISIBLE);
                            detailLayout.setVisibility(View.GONE);
                            todayListView.changeState();
                            tomorrowListView.changeState();
                            nextTomorrowListView.changeState();
                        }

                        if(msg.obj.toString().equals("2")){
                            progressTxt.setVisibility(View.GONE);
                            detailLayout.setVisibility(View.VISIBLE);
//                            ToastCustom.showToast(getApplicationContext(),"没有了╮(╯▽╰)╭");
                            todayListView.changeState();
                            tomorrowListView.changeState();
                            nextTomorrowListView.changeState();
                        }


                    }else{

                        ToastCustom.showToast(getApplicationContext(),"网络异常，请稍后再试!");
                        progressTxt.setVisibility(View.GONE);
                        detailLayout.setVisibility(View.VISIBLE);
                        todayListView.changeState();
                        tomorrowListView.changeState();
                        nextTomorrowListView.changeState();
                    }



                    break;


                case HttpUtil.GET_DETAIL_ONEDAY_SCHEDULE_SUCCESS://获取单天日程成功

                    if(msg.obj != null){

                        Log.d("更新------------->",msg.obj.toString());

                        if(msg.obj.toString().equals("0")){//今天
                            if(todayList.size() == 0){
//                                ToastCustom.showToast(getApplicationContext(),"已经是最新日程");
                            }else{
                                todayAdapter.notiDataChangeList(todayList);

                            }
                        }

                        if(msg.obj.toString().equals("1")){//明天
                            if(tomorrowList.size() == 0){
//                                ToastCustom.showToast(getApplicationContext(),"已经是最新日程");
                            }else{
                                tomorrowAdapter.notiDataChangeList(tomorrowList);

                            }
                        }

                        if(msg.obj.toString().equals("2")){//后天
                            if(nextTomorrowList.size() == 0){
//                                ToastCustom.showToast(getApplicationContext(),"已经是最新日程");
                            }else{
                                nextTomorrowAdapter.notiDataChangeList(nextTomorrowList);
                            }


                        }
                        isGetSchedule = false;
                        //改变显示的状态
                        if(dialog != null) {
                            canCloseDialog(dialog,true);
                            dialog.dismiss();
                        }
                        todayListView.changeState();
                        tomorrowListView.changeState();
                        nextTomorrowListView.changeState();

                    }

                    break;

                case HttpUtil.SEND_DETAIL_SCHEDULE_SUCCESS:

                    if(msg.obj != null){
                        isGetSchedule = true;
                        todayList.clear();
                        tomorrowList.clear();
                        nextTomorrowList.clear();
                        if(msg.obj.toString().equals("0"))
                            HttpUtil.apiGetOneDaySchedule(map, todayList, handler);
                        if(msg.obj.toString().equals("1"))
                            HttpUtil.apiGetOneDaySchedule(map, tomorrowList, handler);
                        if(msg.obj.toString().equals("2"))
                            HttpUtil.apiGetOneDaySchedule(map, nextTomorrowList, handler);

                    }


                    break;

                case HttpUtil.SEND_DETAIL_SCHEDULE_FAILD:
                    isGetSchedule = false;

                    txt.setText("网络异常，请重新加载...");
                    progressBar.setVisibility(View.GONE);
                    canCloseDialog(dialog,true);

                    break;



                case HttpUtil.LOGIN_SUCCESS://登录成功
                    isGetSchedule = false;
                    ToastCustom.showToast(getApplicationContext(),"请在刷新一次");
                    break;

                case HttpUtil.LOGIN_FAILD://登录失败
                    isGetSchedule = false;
                    ToastCustom.showToast(getApplicationContext(),"请重新登录");
                    progressTxt.setVisibility(View.GONE);
                    detailLayout.setVisibility(View.VISIBLE);
                    todayListView.changeState();
                    tomorrowListView.changeState();
                    nextTomorrowListView.changeState();
                    break;


            }





        }
    }




    @Override
    protected void onStop() {

        //开启线程保存数据
        Thread saveThread = new Thread(new Runnable() {
            @Override
            public void run() {

                Looper.prepare();
                todayAdapter.saveFile(todayFileName);
                tomorrowAdapter.saveFile(tomorrowFileName);
                nextTomorrowAdapter.saveFile(nextTomorrowFileName);
//                FileUtil.deleteDetailFile(new File(FileUtil.detailCachePath),new String[]{todayFileName,tomorrowFileName,nextTomorrowFileName});
            }
        });
//        saveThread.setPriority(Thread.MAX_PRIORITY);
        saveThread.start();


        Log.e("-------------->","onStop 保存文件");

        super.onStop();
    }

    @Override
    protected void onDestroy() {

        nextTomorrowList = null;
        todayList = null;
        tomorrowList = null;
        map = null;

        super.onDestroy();
    }

}
